package com.winterwar.web;

import java.net.InetSocketAddress;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.spy.memcached.MemcachedClient;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.DynaActionForm;
import org.apache.struts.actions.DispatchAction;

import com.winterwar.base.Convention;
import com.winterwar.base.Event;
import com.winterwar.base.Slot;
import com.winterwar.service.ConventionManager;
import com.winterwar.service.SlotManager;

public class SlotAction  extends DispatchAction{
	
	private static Log log = LogFactory.getLog(SlotAction.class);
	private SlotManager mgr;
	private ConventionManager conMgr;
	
	public void setConventionManager(ConventionManager mgr){
		this.conMgr = mgr;
	}
	
	public void setManager(SlotManager mgr){
		this.mgr = mgr;
	}
	
	public ActionForward delete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	throws Exception {
		if(log.isDebugEnabled()){
			log.debug("Starting delete...");
		}
		mgr.remove(request.getParameter("slot.id"));
		ActionMessages messages = new ActionMessages();
		messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("slot.deleted"));
		saveMessages(request, messages);
		return list(mapping, form, request, response);
	}

	public ActionForward save(ActionMapping mapping, ActionForm form,
				HttpServletRequest request, HttpServletResponse response)
	throws Exception {
		if(log.isDebugEnabled()){
			log.debug("Starting save...");
		}
		Random gen = new Random(new Date().getTime());
		HttpSession session = request.getSession();
		MemcachedClient cacheClient = new MemcachedClient(new InetSocketAddress("localhost", 11211));
		DateFormat format = new SimpleDateFormat("mm/dd/yyyy hh a");
		
		if(session.getAttribute("randFormID").toString().equals(request.getParameter("formID").toString())){
			session.setAttribute("randFormID", gen.nextInt() + "");
			String startDate = request.getParameter("slot.startDateDate") + " " 
								+ request.getParameter("slot.startDateHour") + " " 
								+ request.getParameter("slot.startDateAMPM");
			String endDate = request.getParameter("slot.endDateDate") + " " 
								+ request.getParameter("slot.endDateHour") + " " 
								+ request.getParameter("slot.endDateAMPM");
			
			Slot slot = new Slot();
			String slotID = request.getParameter("slot.slotID");
			if(slotID != null && slotID.length() > 0 && slotID.compareTo("") != 0)
				slot.setSlotID(Integer.valueOf(slotID));
			else
				slot.setSlotID(null);
			slot.setSlotName(request.getParameter("slot.slotName"));
			slot.setStartDate(format.parse(startDate));
			slot.setEndDate(format.parse(endDate));
			String conID = request.getParameter("conID");
			if(conID == null || conID.compareTo("") == 0 || conID.length() < 1){
				conID = (cacheClient.get("Curr_Con_ID") != null) ? cacheClient.get("Curr_Con_ID").toString() : null;;
				if(conID == null || conID.equals("")){
					conID = conMgr.getCurrentCon().getConID().toString();
				}
			}
			slot.setConID(Integer.valueOf(conID));
			
			slot.setIsLocked(new Boolean(request.getParameter("slot.isLocked") != null));
			
			mgr.save(slot);
			
			ActionMessages messages = new ActionMessages();
			messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("slot.saved"));
			saveMessages(request, messages);
		}
		return list(mapping, form, request, response);
	}

	public ActionForward edit(ActionMapping mapping, ActionForm form,
					HttpServletRequest request, HttpServletResponse response)
	throws Exception {
		if(log.isDebugEnabled()){
			log.debug("Starting edit...");
		}
		DynaActionForm slotForm = (DynaActionForm) form;
		String slotID = request.getParameter("slotID");
		request.setAttribute("conID", request.getParameter("conID"));
		
		if(slotID != null){
			Slot slot = mgr.get(slotID);
			if(slot == null){
				ActionMessages errors = new ActionMessages();
				errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("slot.missing"));
				saveErrors(request, errors);
				
				return mapping.findForward("list");
			}
			slotForm.set("slot", slot);
			request.setAttribute("persSlot", slot);
		}
		return mapping.findForward("edit");
	}
	
	public ActionForward list(ActionMapping mapping, ActionForm form,
						HttpServletRequest request, HttpServletResponse response)
	throws Exception {
		if(log.isDebugEnabled()){
			log.debug("Starting list...");
		}
		request.setAttribute("slots", mgr.getAll());
		
		return mapping.findForward("list");
	}
	
	public ActionForward listByCon(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	throws Exception {
		MemcachedClient cacheClient = new MemcachedClient(new InetSocketAddress("localhost", 11211));
		if(log.isDebugEnabled()){
			log.debug("Starting list...");
		}
		String conID = request.getParameter("conID");
		String event = request.getParameter("fromevents");
		if(conID == null){
			conID = (cacheClient.get("Curr_Con_ID") != null) ? cacheClient.get("Curr_Con_ID").toString() : null;;
			if(conID == null || conID.equals("")){
				conID = conMgr.getCurrentCon().getConID().toString();
			}
		}
		request.setAttribute("conID", conID);
		request.setAttribute("slots", mgr.getAllByCon(conID));
		request.setAttribute("cons", conMgr.getAll());
		if(event != null && event.compareTo("true") == 0){
			return mapping.findForward("eventList");
		}
		return mapping.findForward("list");
	}
	@SuppressWarnings("unchecked")
	public ActionForward slotView(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	throws Exception {
		if(log.isDebugEnabled()){
		log.debug("Starting list...");
		}
		String slotID = request.getParameter("slotID");
		Slot slot = mgr.get(slotID);
		request.setAttribute("slot", slot);
		Set<Event> events = slot.getEvents();
		Set listEvents = new HashSet();
		for(Event e : events){
			if(e.getStatus() == 3) listEvents.add(e);
		}
		request.setAttribute("events", listEvents);
		request.setAttribute("parentSlotID", request.getParameter("parentSlotID"));
		return mapping.findForward("slotView");
	}
}
